package com.xqzgj.system.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import org.springframework.stereotype.Service;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.xqzgj.common.core.domain.AjaxResult;
import com.xqzgj.system.service.IAiChatService;

@Service
public class AiChatServiceImpl implements IAiChatService {

    private static final String API_KEY = "sk-911521b7e3884b95979ef75287eb0533";
    private List<Message> messageHistory = new ArrayList<>();

    @Override
    public AjaxResult sendMessage(String content) {
        try {
            Generation gen = new Generation();

            // 如果是新对话，添加系统消息
            if (messageHistory.isEmpty()) {
                Message systemMsg = Message.builder()
                        .role(Role.SYSTEM.getValue())
                        .content("You are a helpful assistant.")
                        .build();
                messageHistory.add(systemMsg);
            }

            // 添加用户消息
            Message userMsg = Message.builder()
                    .role(Role.USER.getValue())
                    .content(content)
                    .build();
            messageHistory.add(userMsg);

            GenerationParam param = GenerationParam.builder()
                    .apiKey(API_KEY)
                    .model("qwen-plus")
                    .messages(messageHistory)
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .build();

            GenerationResult result = gen.call(param);
            Message assistantMessage = result.getOutput().getChoices().get(0).getMessage();
            messageHistory.add(assistantMessage);

            return AjaxResult.success(assistantMessage.getContent());

        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            return AjaxResult.error("AI服务调用失败：" + e.getMessage());
        }
    }

    @Override
    public AjaxResult clearChat() {
        messageHistory.clear();
        return AjaxResult.success("对话已清除");
    }
}